import 'dart:async';
import 'package:dio/dio.dart';
import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
import './req_interceptor.dart';

// url
class _RequestConfig {
  static String baseUrl = 'https://xxx.com';
  static String otherUrl = 'https://otherApi.com';
  static String testPath = 'test/path';
  static const CONNECT_TIMEOUT = 7000;
}

class RequestManager {
  static RequestManager _instance = RequestManager._internal();
  late Dio _dio;
  factory RequestManager() => _instance;
  RequestManager._internal() {
    if (null == _dio) {
      var options = BaseOptions(
        baseUrl: _RequestConfig.baseUrl,
        connectTimeout: _RequestConfig.CONNECT_TIMEOUT,
      );
      _dio = new Dio(options);
      _dio.interceptors.add(LogInterceptor(responseBody: true)); // 开启日志
      _dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) {
          // request hook
          return handler.next(options);
        },
        onResponse: (response, handler) {
          // response hook
          var status = response.statusCode;
          if (status == 400) {
            //
          }
          return handler.next(response);
        },
        onError: (DioError e, handler) {
          // error hook
          return handler.next(e);
        }
      ));
      var cookieJar = CookieJar();
      _dio.interceptors.add(CookieManager(cookieJar));
    }
  }
  get(api, params) async {
    Response response;
    try {
      response = await _dio.get(api, queryParameters: params);
    } on DioError catch (e) {
      return e;
    }
    return response;
  }
  post(api, params) async {
    Response response;
    try {
      response = await _dio.post(api, data: params);
    } on DioError catch (e) {
      return e;
    }
    return response;
  }
  delete(api, params) async {
    Response response;
    try {
      response = await _dio.delete(api, data: params);
    } on DioError catch (e) {
      return e;
    }
    return response;
  }
  put(api, params) async {
    Response response;
    try {
      response = await _dio.put(api, data: params);
    } on DioError catch (e) {
      return e;
    }
    return response;
  }
}
